import UserManagement from './UserManagement'
import { revalidatePath } from 'next/cache'

import { updateUser, getAllUsers, createUser, deleteUser } from '@/lib/userService'

import { getCampuses } from '@/lib/campusService'

async function updateUserWrapper(userId, user) {
  'use server'
  try {
    await updateUser(userId, user)
    revalidatePath('/admin/users')
    return { success: true }
  } catch (error) {
    console.error('Failed to update user:', error)
    return { error: '更新用户失败' }
  }
}

async function deleteUserWrapper(userId) {
  'use server'
  try {
    await deleteUser(userId)
    revalidatePath('/admin/users')
    return { success: true }
  } catch (error) {
    console.error('Failed to delete user:', error)
    return { error: '删除用户失败' }
  }
}

// handle add user
async function addUser(user) {
  'use server'
  try {
    await createUser(user)
    revalidatePath('/admin/users')
    return { success: true }
  } catch (error) {
    console.error('Failed to add user:', error)
    return { error: '添加用户失败' }
  }
}

export default async function UsersPage() {
  const campuses = await getCampuses({})
  return (
    <UserManagement
      getUsers={getAllUsers}
      initialCampuses={campuses}
      updateUser={updateUserWrapper}
      addUser={addUser}
      deleteUser={deleteUserWrapper}
    />
  )
}